ab2c72d675313f3e9985da1bb0b3b71b1488f00d
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?
2 # See design.doc
3
4 if($wgUseTeX) include_once( "Math.php" );
5
6 class OutputPage {
7 var $mHeaders, $mCookies, $mMetatags, $mKeywords;
8 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
9 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
10 var $mSubtitle, $mRedirect, $mAutonumber, $mHeadtext;
11 var $mLastModified, $mCategoryLinks;
12
13 var $mDTopen, $mLastSection; # Used for processing DL, PRE
14 var $mLanguageLinks, $mSupressQuickbar;
15 var $mOnloadHandler;
16
17 function OutputPage()
18 {
19 $this->mHeaders = $this->mCookies = $this->mMetatags =
20 $this->mKeywords = $this->mLinktags = array();
21 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
22 $this->mLastSection = $this->mRedirect = $this->mLastModified =
23 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
24 $this->mOnloadHandler = "";
25 $this->mIsarticle = $this->mPrintable = true;
26 $this->mSupressQuickbar = $this->mDTopen = $this->mPrintable = false;
27 $this->mLanguageLinks = array();
28 $this->mCategoryLinks = array() ;
29 $this->mAutonumber = 0;
30 }
31
32 function addHeader( $name, $val ) { array_push( $this->mHeaders, "$name: $val" ) ; }
33 function addCookie( $name, $val ) { array_push( $this->mCookies, array( $name, $val ) ); }
34 function redirect( $url ) { $this->mRedirect = $url; }
35
36 # To add an http-equiv meta tag, precede the name with "http:"
37 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
38 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
39 function addLink( $rel, $rev, $target ) { array_push( $this->mLinktags, array( $rel, $rev, $target ) ); }
40
41 function checkLastModified ( $timestamp )
42 {
43 global $wgLang, $wgCachePages, $wgUser;
44 if( !$wgCachePages ) {
45 wfDebug( "CACHE DISABLED\n", false );
46 return;
47 }
48 if( preg_match( '/MSIE ([1-4]|5\.0)/', $_SERVER["HTTP_USER_AGENT"] ) ) {
49 # IE 5.0 has probs with our caching
50 wfDebug( "-- bad client, not caching\n", false );
51 return;
52 }
53 if( $wgUser->getOption( "nocache" ) ) {
54 wfDebug( "USER DISABLED CACHE\n", false );
55 return;
56 }
57
58 $lastmod = gmdate( "D, j M Y H:i:s", wfTimestamp2Unix(
59 max( $timestamp, $wgUser->mTouched ) ) ) . " GMT";
60
61 if( !empty( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ) {
62 # IE sends sizes after the date like this:
63 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
64 # this breaks strtotime().
65 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
66 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
67 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
68 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
69
70 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
71 # Make sure you're in a place you can leave when you call us!
72 header( "HTTP/1.0 304 Not Modified" );
73 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
74 header( "Cache-Control: private, must-revalidate, max-age=0" );
75 header( "Last-Modified: {$lastmod}" );
76 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
77 $this->reportTime(); # For profiling
78 wfAbruptExit();
79 } else {
80 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
81 $this->mLastModified = $lastmod;
82 }
83 } else {
84 wfDebug( "We're confused.\n", false );
85 $this->mLastModified = $lastmod;
86 }
87 }
88
89 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
90 function setHTMLtitle( $name ) { $this->mHTMLtitle = $name; }
91 function setPageTitle( $name ) { $this->mPagetitle = $name; }
92 function getPageTitle() { return $this->mPagetitle; }
93 function setSubtitle( $str ) { $this->mSubtitle = $str; }
94 function getSubtitle() { return $this->mSubtitle; }
95 function setArticleFlag( $v ) { $this->mIsarticle = $v; }
96 function isArticle() { return $this->mIsarticle; }
97 function setPrintable() { $this->mPrintable = true; }
98 function isPrintable() { return $this->mPrintable; }
99 function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
100 function getOnloadHandler() { return $this->mOnloadHandler; }
101
102 function getLanguageLinks() {
103 global $wgTitle, $wgLanguageCode;
104 global $wgDBconnection, $wgDBname;
105 return $this->mLanguageLinks;
106 }
107 function supressQuickbar() { $this->mSupressQuickbar = true; }
108 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
109
110 function addHTML( $text ) { $this->mBodytext .= $text; }
111 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
112 function debug( $text ) { $this->mDebugtext .= $text; }
113
114 # First pass--just handle <nowiki> sections, pass the rest off
115 # to doWikiPass2() which does all the real work.
116 #
117
118 function addWikiText( $text, $linestart = true )
119 {
120 global $wgUseTeX;
121 $fname = "OutputPage::addWikiText";
122 wfProfileIn( $fname );
123 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
124 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
125 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
126 $nwlist = array();
127 $nwsecs = 0;
128 $mathlist = array();
129 $mathsecs = 0;
130 $prelist = array ();
131 $presecs = 0;
132 $stripped = "";
133 $stripped2 = "";
134 $stripped3 = "";
135
136 while ( "" != $text ) {
137 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
138 $stripped .= $p[0];
139 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
140 else {
141 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
142 ++$nwsecs;
143 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
144 $stripped .= $unique . $nwsecs . "s";
145 $text = $q[1];
146 }
147 }
148
149 if( $wgUseTeX ) {
150 while ( "" != $stripped ) {
151 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
152 $stripped2 .= $p[0];
153 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
154 else {
155 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
156 ++$mathsecs;
157 $mathlist[$mathsecs] = renderMath($q[0]);
158 $stripped2 .= $unique2 . $mathsecs . "s";
159 $stripped = $q[1];
160 }
161 }
162 } else {
163 $stripped2 = $stripped;
164 }
165
166 while ( "" != $stripped2 ) {
167 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
168 $stripped3 .= $p[0];
169 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
170 else {
171 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
172 ++$presecs;
173 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>";
174 $stripped3 .= $unique3 . $presecs . "s";
175 $stripped2 = $q[1];
176 }
177 }
178
179 $text = $this->doWikiPass2( $stripped3, $linestart );
180
181 $specialChars = array("\\", "$");
182 $escapedChars = array("\\\\", "\\$");
183 for ( $i = 1; $i <= $presecs; ++$i ) {
184 $text = preg_replace( "/{$unique3}{$i}s/", str_replace( $specialChars,
185 $escapedChars, $prelist[$i] ), $text );
186 }
187
188 for ( $i = 1; $i <= $mathsecs; ++$i ) {
189 $text = preg_replace( "/{$unique2}{$i}s/", str_replace( $specialChars,
190 $escapedChars, $mathlist[$i] ), $text );
191 }
192
193 for ( $i = 1; $i <= $nwsecs; ++$i ) {
194 $text = preg_replace( "/{$unique}{$i}s/", str_replace( $specialChars,
195 $escapedChars, $nwlist[$i] ), $text );
196 }
197 $this->addHTML( $text );
198 wfProfileOut( $fname );
199 }
200
201 function sendCacheControl() {
202 global $wgUseGzip;
203 if( $this->mLastModified != "" ) {
204 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
205 header( "Cache-Control: private, must-revalidate, max-age=0" );
206 header( "Last-modified: {$this->mLastModified}" );
207 if( $wgUseGzip ) {
208 # We should put in Accept-Encoding, but IE chokes on anything but
209 # User-Agent in a Vary: header (at least through 6.0)
210 header( "Vary: User-Agent" );
211 }
212 } else {
213 wfDebug( "** no caching **\n", false );
214 header( "Cache-Control: no-cache" ); # Experimental - see below
215 header( "Pragma: no-cache" );
216 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
217 }
218 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
219 }
220
221 # Finally, all the text has been munged and accumulated into
222 # the object, let's actually output it:
223 #
224 function output()
225 {
226 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
227 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
228
229 $fname = "OutputPage::output";
230 wfProfileIn( $fname );
231
232 $sk = $wgUser->getSkin();
233
234 $this->sendCacheControl();
235
236 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
237 header( "Content-language: {$wgLanguageCode}" );
238
239 if ( "" != $this->mRedirect ) {
240 header( "Location: {$this->mRedirect}" );
241 return;
242 }
243
244 $exp = time() + $wgCookieExpiration;
245 foreach( $this->mCookies as $name => $val ) {
246 setcookie( $name, $val, $exp, "/" );
247 }
248
249 $sk->outputPage( $this );
250 flush();
251 }
252
253 function out( $ins )
254 {
255 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
256 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
257 $outs = $ins;
258 } else {
259 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
260 if ( false === $outs ) { $outs = $ins; }
261 }
262 print $outs;
263 }
264
265 function setEncodings()
266 {
267 global $wgInputEncoding, $wgOutputEncoding;
268 global $wgUser, $wgLang;
269
270 $wgInputEncoding = strtolower( $wgInputEncoding );
271
272 if( $wgUser->getOption( 'altencoding' ) ) {
273 $wgLang->setAltEncoding();
274 return;
275 }
276
277 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
278 $wgOutputEncoding = strtolower( $wgOutputEncoding );
279 return;
280 }
281
282 /*
283 # This code is unused anyway!
284 # Commenting out. --bv 2003-11-15
285
286 $a = explode( ",", $_SERVER['HTTP_ACCEPT_CHARSET'] );
287 $best = 0.0;
288 $bestset = "*";
289
290 foreach ( $a as $s ) {
291 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
292 $set = $m[1];
293 $q = (float)($m[2]);
294 } else {
295 $set = $s;
296 $q = 1.0;
297 }
298 if ( $q > $best ) {
299 $bestset = $set;
300 $best = $q;
301 }
302 }
303 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
304 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
305 $wgOutputEncoding = strtolower( $bestset );
306
307 # Disable for now
308 #
309 */
310 $wgOutputEncoding = $wgInputEncoding;
311 }
312
313 function reportTime()
314 {
315 global $wgRequestTime, $wgDebugLogFile;
316 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
317
318 list( $usec, $sec ) = explode( " ", microtime() );
319 $now = (float)$sec + (float)$usec;
320
321 list( $usec, $sec ) = explode( " ", $wgRequestTime );
322 $start = (float)$sec + (float)$usec;
323 $elapsed = $now - $start;
324
325 if ( "" != $wgDebugLogFile ) {
326 $prof = wfGetProfilingOutput( $start, $elapsed );
327 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
328 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
329 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
330 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
331 if( !empty( $_SERVER['HTTP_FROM'] ) )
332 $forward .= " from " . $_SERVER['HTTP_FROM'];
333 if( $forward )
334 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
335 if($wgUser->getId() == 0)
336 $forward .= " anon";
337 $log = sprintf( "%s\t%04.3f\t%s\n",
338 gmdate( "YmdHis" ), $elapsed,
339 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
340 error_log( $log . $prof, 3, $wgDebugLogFile );
341 }
342 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
343 $elapsed );
344 return $com;
345 }
346
347 # Note: these arguments are keys into wfMsg(), not text!
348 #
349 function errorpage( $title, $msg )
350 {
351 global $wgTitle;
352
353 $this->mDebugtext .= "Original title: " .
354 $wgTitle->getPrefixedText() . "\n";
355 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
356 $this->setPageTitle( wfMsg( $title ) );
357 $this->setRobotpolicy( "noindex,nofollow" );
358 $this->setArticleFlag( false );
359
360 $this->mBodytext = "";
361 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
362 $this->returnToMain( false );
363
364 $this->output();
365 wfAbruptExit();
366 }
367
368 function sysopRequired()
369 {
370 global $wgUser;
371
372 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
373 $this->setPageTitle( wfMsg( "sysoptitle" ) );
374 $this->setRobotpolicy( "noindex,nofollow" );
375 $this->setArticleFlag( false );
376 $this->mBodytext = "";
377
378 $sk = $wgUser->getSkin();
379 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
380 $this->addHTML( wfMsg( "sysoptext", $ap ) );
381 $this->returnToMain();
382 }
383
384 function developerRequired()
385 {
386 global $wgUser;
387
388 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
389 $this->setPageTitle( wfMsg( "developertitle" ) );
390 $this->setRobotpolicy( "noindex,nofollow" );
391 $this->setArticleFlag( false );
392 $this->mBodytext = "";
393
394 $sk = $wgUser->getSkin();
395 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
396 $this->addHTML( wfMsg( "developertext", $ap ) );
397 $this->returnToMain();
398 }
399
400 function databaseError( $fname )
401 {
402 global $wgUser, $wgCommandLineMode;
403
404 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
405 $this->setRobotpolicy( "noindex,nofollow" );
406 $this->setArticleFlag( false );
407
408 if ( $wgCommandLineMode ) {
409 $msg = wfMsgNoDB( "dberrortextcl" );
410 } else {
411 $msg = wfMsgNoDB( "dberrortext" );
412 }
413
414 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
415 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
416 $msg = str_replace( "$3", wfLastErrno(), $msg );
417 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
418
419 if ( $wgCommandLineMode ) {
420 print "$msg\n";
421 wfAbruptExit();
422 }
423 $sk = $wgUser->getSkin();
424 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
425 wfMsgNoDB( "searchingwikipedia" ) );
426 $msg = str_replace( "$5", $shlink, $msg );
427
428 $this->mBodytext = $msg;
429 $this->output();
430 wfAbruptExit();
431 }
432
433 function readOnlyPage( $source = "", $protected = false )
434 {
435 global $wgUser, $wgReadOnlyFile;
436
437 $this->setRobotpolicy( "noindex,nofollow" );
438 $this->setArticleFlag( false );
439
440 if( $protected ) {
441 $this->setPageTitle( wfMsg( "viewsource" ) );
442 $this->addWikiText( wfMsg( "protectedtext" ) );
443 } else {
444 $this->setPageTitle( wfMsg( "readonly" ) );
445 $reason = file_get_contents( $wgReadOnlyFile );
446 $this->addHTML( wfMsg( "readonlytext", $reason ) );
447 }
448
449 if($source) {
450 $rows = $wgUser->getOption( "rows" );
451 $cols = $wgUser->getOption( "cols" );
452 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
453 htmlspecialchars( $source ) . "\n</textarea>";
454 $this->addHTML( $text );
455 }
456
457 $this->returnToMain( false );
458 }
459
460 function fatalError( $message )
461 {
462 $this->setPageTitle( wfMsg( "internalerror" ) );
463 $this->setRobotpolicy( "noindex,nofollow" );
464 $this->setArticleFlag( false );
465
466 $this->mBodytext = $message;
467 $this->output();
468 wfAbruptExit();
469 }
470
471 function unexpectedValueError( $name, $val )
472 {
473 $this->fatalError( wfMsg( "unexpected", $name, $val ) );
474 }
475
476 function fileCopyError( $old, $new )
477 {
478 $this->fatalError( wfMsg( "filecopyerror", $old, $new ) );
479 }
480
481 function fileRenameError( $old, $new )
482 {
483 $this->fatalError( wfMsg( "filerenameerror", $old, $new ) );
484 }
485
486 function fileDeleteError( $name )
487 {
488 $this->fatalError( wfMsg( "filedeleteerror", $name ) );
489 }
490
491 function fileNotFoundError( $name )
492 {
493 $this->fatalError( wfMsg( "filenotfound", $name ) );
494 }
495
496 function returnToMain( $auto = true )
497 {
498 global $wgUser, $wgOut, $returnto;
499
500 $sk = $wgUser->getSkin();
501 if ( "" == $returnto ) {
502 $returnto = wfMsg( "mainpage" );
503 }
504 $link = $sk->makeKnownLink( $returnto, "" );
505
506 $r = wfMsg( "returnto", $link );
507 if ( $auto ) {
508 $wgOut->addMeta( "http:Refresh", "10;url=" .
509 wfLocalUrlE( wfUrlencode( $returnto ) ) );
510 }
511 $wgOut->addHTML( "\n<p>$r\n" );
512 }
513
514
515 function categoryMagic ()
516 {
517 global $wgTitle , $wgUseCategoryMagic ;
518 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
519 $id = $wgTitle->getArticleID() ;
520 $cat = ucfirst ( wfMsg ( "category" ) ) ;
521 $ti = $wgTitle->getText() ;
522 $ti = explode ( ":" , $ti , 2 ) ;
523 if ( $cat != $ti[0] ) return "" ;
524 $r = "<br break=all>\n" ;
525
526 $articles = array() ;
527 $parents = array () ;
528 $children = array() ;
529
530
531 global $wgUser ;
532 $sk = $wgUser->getSkin() ;
533 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
534 $res = wfQuery ( $sql, DB_READ ) ;
535 while ( $x = wfFetchObject ( $res ) )
536 {
537 # $t = new Title ;
538 # $t->newFromDBkey ( $x->l_from ) ;
539 # $t = $t->getText() ;
540 $t = $x->l_from ;
541 $y = explode ( ":" , $t , 2 ) ;
542 if ( count ( $y ) == 2 && $y[0] == $cat ) {
543 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
544 } else {
545 array_push ( $articles , $sk->makeLink ( $t ) ) ;
546 }
547 }
548 wfFreeResult ( $res ) ;
549
550 # Children
551 if ( count ( $children ) > 0 )
552 {
553 asort ( $children ) ;
554 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
555 $r .= implode ( ", " , $children ) ;
556 }
557
558 # Articles
559 if ( count ( $articles ) > 0 )
560 {
561 asort ( $articles ) ;
562 $h = wfMsg( "category_header", $ti[1] );
563 $r .= "<h2>{$h}</h2>\n" ;
564 $r .= implode ( ", " , $articles ) ;
565 }
566
567
568 return $r ;
569 }
570
571 function getHTMLattrs ()
572 {
573 $htmlattrs = array( # Allowed attributes--no scripting, etc.
574 "title", "align", "lang", "dir", "width", "height",
575 "bgcolor", "clear", /* BR */ "noshade", /* HR */
576 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
577 /* FONT */ "type", "start", "value", "compact",
578 /* For various lists, mostly deprecated but safe */
579 "summary", "width", "border", "frame", "rules",
580 "cellspacing", "cellpadding", "valign", "char",
581 "charoff", "colgroup", "col", "span", "abbr", "axis",
582 "headers", "scope", "rowspan", "colspan", /* Tables */
583 "id", "class", "name", "style" /* For CSS */
584 );
585 return $htmlattrs ;
586 }
587
588 function fixTableTags ( $t )
589 {
590 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
591 $htmlattrs = $this->getHTMLattrs() ;
592
593 # Strip non-approved attributes from the tag
594 $t = preg_replace(
595 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
596 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
597 $t);
598
599 return trim ( $t ) ;
600 }
601
602 function doTableStuff ( $t )
603 {
604 $t = explode ( "\n" , $t ) ;
605 $td = array () ; # Is currently a td tag open?
606 $ltd = array () ; # Was it TD or TH?
607 $tr = array () ; # Is currently a tr tag open?
608 $ltr = array () ; # tr attributes
609 foreach ( $t AS $k => $x )
610 {
611 $x = rtrim ( $x ) ;
612 $fc = substr ( $x , 0 , 1 ) ;
613 if ( "{|" == substr ( $x , 0 , 2 ) )
614 {
615 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
616 array_push ( $td , false ) ;
617 array_push ( $ltd , "" ) ;
618 array_push ( $tr , false ) ;
619 array_push ( $ltr , "" ) ;
620 }
621 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
622 else if ( "|}" == substr ( $x , 0 , 2 ) )
623 {
624 $z = "</table>\n" ;
625 $l = array_pop ( $ltd ) ;
626 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
627 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
628 array_pop ( $ltr ) ;
629 $t[$k] = $z ;
630 }
631 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
632 {
633 $z = trim ( substr ( $x , 2 ) ) ;
634 $t[$k] = "<caption>{$z}</caption>\n" ;
635 }*/
636 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
637 {
638 $x = substr ( $x , 1 ) ;
639 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
640 $z = "" ;
641 $l = array_pop ( $ltd ) ;
642 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
643 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
644 array_pop ( $ltr ) ;
645 $t[$k] = $z ;
646 array_push ( $tr , false ) ;
647 array_push ( $td , false ) ;
648 array_push ( $ltd , "" ) ;
649 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
650 }
651 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
652 {
653 if ( "|+" == substr ( $x , 0 , 2 ) )
654 {
655 $fc = "+" ;
656 $x = substr ( $x , 1 ) ;
657 }
658 $after = substr ( $x , 1 ) ;
659 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
660 $after = explode ( "||" , $after ) ;
661 $t[$k] = "" ;
662 foreach ( $after AS $theline )
663 {
664 $z = "" ;
665 $tra = array_pop ( $ltr ) ;
666 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
667 array_push ( $tr , true ) ;
668 array_push ( $ltr , "" ) ;
669
670 $l = array_pop ( $ltd ) ;
671 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
672 if ( $fc == "|" ) $l = "TD" ;
673 else if ( $fc == "!" ) $l = "TH" ;
674 else if ( $fc == "+" ) $l = "CAPTION" ;
675 else $l = "" ;
676 array_push ( $ltd , $l ) ;
677 $y = explode ( "|" , $theline , 2 ) ;
678 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
679 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
680 $t[$k] .= $y ;
681 array_push ( $td , true ) ;
682 }
683 }
684 }
685
686 # Closing open td, tr && table
687 while ( count ( $td ) > 0 )
688 {
689 if ( array_pop ( $td ) ) $t[] = "</td>" ;
690 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
691 $t[] = "</table>" ;
692 }
693
694 $t = implode ( "\n" , $t ) ;
695 # $t = $this->removeHTMLtags( $t );
696 return $t ;
697 }
698
699 # Well, OK, it's actually about 14 passes. But since all the
700 # hard lifting is done inside PHP's regex code, it probably
701 # wouldn't speed things up much to add a real parser.
702 #
703 function doWikiPass2( $text, $linestart )
704 {
705 global $wgUser, $wgLang, $wgUseDynamicDates;
706 $fname = "OutputPage::doWikiPass2";
707 wfProfileIn( $fname );
708
709 $text = $this->removeHTMLtags( $text );
710 $text = $this->replaceVariables( $text );
711
712 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
713 $text = str_replace ( "<HR>", "<hr>", $text );
714
715 $text = $this->doAllQuotes( $text );
716 $text = $this->doHeadings( $text );
717 $text = $this->doBlockLevels( $text, $linestart );
718
719 if($wgUseDynamicDates) {
720 global $wgDateFormatter;
721 $text = $wgDateFormatter->reformat( $wgUser->getOption("date"), $text );
722 }
723
724 $text = $this->replaceExternalLinks( $text );
725 $text = $this->replaceInternalLinks ( $text );
726 $text = $this->doTableStuff ( $text ) ;
727
728 $text = $this->magicISBN( $text );
729 $text = $this->magicRFC( $text );
730 $text = $this->formatHeadings( $text );
731
732 $sk = $wgUser->getSkin();
733 $text = $sk->transformContent( $text );
734 $text .= $this->categoryMagic () ;
735
736 wfProfileOut( $fname );
737 return $text;
738 }
739
740 /* private */ function doAllQuotes( $text )
741 {
742 $outtext = "";
743 $lines = explode( "\r\n", $text );
744 foreach ( $lines as $line ) {
745 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
746 }
747 return $outtext;
748 }
749
750 /* private */ function doQuotes( $pre, $text, $mode )
751 {
752 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
753 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
754 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
755 if ( substr ($m[2], 0, 1) == "'" ) {
756 $m[2] = substr ($m[2], 1);
757 if ($mode == "em") {
758 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
759 } else if ($mode == "strong") {
760 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
761 } else if (($mode == "emstrong") || ($mode == "both")) {
762 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
763 } else if ($mode == "strongem") {
764 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
765 } else {
766 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
767 }
768 } else {
769 if ($mode == "strong") {
770 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
771 } else if ($mode == "em") {
772 return $m1_em . $this->doQuotes ( "", $m[2], "" );
773 } else if ($mode == "emstrong") {
774 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
775 } else if (($mode == "strongem") || ($mode == "both")) {
776 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
777 } else {
778 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
779 }
780 }
781 } else {
782 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
783 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
784 if ($mode == "") {
785 return $pre . $text;
786 } else if ($mode == "em") {
787 return $pre . $text_em;
788 } else if ($mode == "strong") {
789 return $pre . $text_strong;
790 } else if ($mode == "strongem") {
791 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
792 } else {
793 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
794 }
795 }
796 }
797
798 /* private */ function doHeadings( $text )
799 {
800 for ( $i = 6; $i >= 1; --$i ) {
801 $h = substr( "======", 0, $i );
802 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
803 "<h{$i}>\\1</h{$i}>\\2", $text );
804 }
805 return $text;
806 }
807
808 # Note: we have to do external links before the internal ones,
809 # and otherwise take great care in the order of things here, so
810 # that we don't end up interpreting some URLs twice.
811
812 /* private */ function replaceExternalLinks( $text )
813 {
814 $fname = "OutputPage::replaceExternalLinks";
815 wfProfileIn( $fname );
816 $text = $this->subReplaceExternalLinks( $text, "http", true );
817 $text = $this->subReplaceExternalLinks( $text, "https", true );
818 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
819 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
820 $text = $this->subReplaceExternalLinks( $text, "news", false );
821 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
822 wfProfileOut( $fname );
823 return $text;
824 }
825
826 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
827 {
828 global $wgUser, $printable;
829 global $wgAllowExternalImages;
830
831
832 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
833 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
834
835 # this is the list of separators that should be ignored if they
836 # are the last character of an URL but that should be included
837 # if they occur within the URL, e.g. "go to www.foo.com, where .."
838 # in this case, the last comma should not become part of the URL,
839 # but in "www.foo.com/123,2342,32.htm" it should.
840 $sep = ",;\.:";
841 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
842 $images = "gif|png|jpg|jpeg";
843
844 # PLEASE NOTE: The curly braces { } are not part of the regex,
845 # they are interpreted as part of the string (used to tell PHP
846 # that the content of the string should be inserted there).
847 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
848 "((?i){$images})([^{$uc}]|$)/";
849
850 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
851 $sk = $wgUser->getSkin();
852
853 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
854 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
855 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
856 }
857 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
858 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
859 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
860 "</a>\\5", $s );
861 $s = str_replace( $unique, $protocol, $s );
862
863 $a = explode( "[{$protocol}:", " " . $s );
864 $s = array_shift( $a );
865 $s = substr( $s, 1 );
866
867 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
868 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
869
870 foreach ( $a as $line ) {
871 if ( preg_match( $e1, $line, $m ) ) {
872 $link = "{$protocol}:{$m[1]}";
873 $trail = $m[2];
874 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
875 else { $text = wfEscapeHTML( $link ); }
876 } else if ( preg_match( $e2, $line, $m ) ) {
877 $link = "{$protocol}:{$m[1]}";
878 $text = $m[2];
879 $trail = $m[3];
880 } else {
881 $s .= "[{$protocol}:" . $line;
882 continue;
883 }
884 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
885 else $paren = "";
886 $la = $sk->getExternalLinkAttributes( $link, $text );
887 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
888
889 }
890 return $s;
891 }
892
893 /* private */ function replaceInternalLinks( $s )
894 {
895 global $wgTitle, $wgUser, $wgLang;
896 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
897 global $wgNamespacesWithSubpages, $wgLanguageCode;
898 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
899
900 wfProfileIn( "$fname-setup" );
901 $tc = Title::legalChars() . "#";
902 $sk = $wgUser->getSkin();
903
904 $a = explode( "[[", " " . $s );
905 $s = array_shift( $a );
906 $s = substr( $s, 1 );
907
908 $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD";
909
910 # Special and Media are pseudo-namespaces; no pages actually exist in them
911 $image = Namespace::getImage();
912 $special = Namespace::getSpecial();
913 $media = Namespace::getMedia();
914 $nottalk = !Namespace::isTalk( $wgTitle->getNamespace() );
915 wfProfileOut( "$fname-setup" );
916
917 foreach ( $a as $line ) {
918 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
919 $text = $m[2];
920 $trail = $m[3];
921 } else { # Invalid form; output directly
922 $s .= "[[" . $line ;
923 continue;
924 }
925
926 /* Valid link forms:
927 Foobar -- normal
928 :Foobar -- override special treatment of prefix (images, language links)
929 /Foobar -- convert to CurrentPage/Foobar
930 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
931 */
932 $c = substr($m[1],0,1);
933 $noforce = ($c != ":");
934 if( $c == "/" ) { # subpage
935 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
936 $m[1]=substr($m[1],1,strlen($m[1])-2);
937 $noslash=$m[1];
938 } else {
939 $noslash=substr($m[1],1);
940 }
941 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
942 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
943 if(!$text) {
944 $text= $m[1];
945 } # this might be changed for ugliness reasons
946 } else {
947 $link = $noslash; # no subpage allowed, use standard link
948 }
949 } elseif( $noforce ) { # no subpage
950 $link = $m[1];
951 } else {
952 $link = substr( $m[1], 1 );
953 }
954 if( empty( $text ) )
955 $text = $link;
956
957 $nt = Title::newFromText( $link );
958 if( !$nt ) {
959 $s .= "[[" . $line;
960 continue;
961 }
962 $ns = $nt->getNamespace();
963 $iw = $nt->getInterWiki();
964 if( $noforce ) {
965 if( $iw && $wgInterwikiMagic && $nottalk && $wgLang->getLanguageName( $iw ) ) {
966 array_push( $this->mLanguageLinks, $nt->getPrefixedText() );
967 $s .= $trail;
968 /* CHECK MERGE @@@
969 } else if ( "media" == $pre ) {
970 $nt = Title::newFromText( $suf );
971 $name = $nt->getDBkey();
972 if ( "" == $text ) { $text = $nt->GetText(); }
973
974 $wgLinkCache->addImageLink( $name );
975 $s .= $sk->makeMediaLink( $name,
976 wfImageUrl( $name ), $text );
977 $s .= $trail;
978 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
979 $l = $sk->makeLink ( $pre.":".ucfirst( $m[2] ), ucfirst ( $m[2] ) ) ;
980 array_push ( $this->mCategoryLinks , $l ) ;
981 $s .= $trail ;
982 } else {
983 $l = $wgLang->getLanguageName( $pre );
984 if ( "" == $l or !$wgInterwikiMagic or Namespace::isTalk( $wgTitle->getNamespace() ) ) {
985 if ( "" == $text ) {
986 $text = $link;
987 }
988 $s .= $sk->makeLink( $link, $text, "", $trail );
989 } else if ( $pre != $wgLanguageCode ) {
990 array_push( $this->mLanguageLinks, "$pre:$suf" );
991 $s .= $trail;
992 }
993 */
994 continue;
995 }
996 if( $ns == $image ) {
997 $s .= $sk->makeImageLinkObj( $nt, $text ) . $trail;
998 $wgLinkCache->addImageLinkObj( $nt );
999 continue;
1000 }
1001 /* CHECK MERGE @@@
1002 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
1003 # $link = substr( $link, 2 );
1004 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1005 } else {
1006 if ( "" == $text ) { $text = $link; }
1007 # Hotspot:
1008 $s .= $sk->makeLink( $link, $text, "", $trail );
1009 */
1010 }
1011 if( $ns == $media ) {
1012 $s .= $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1013 $wgLinkCache->addImageLinkObj( $nt );
1014 continue;
1015 } elseif( $ns == $special ) {
1016 $s .= $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1017 continue;
1018 }
1019 $s .= $sk->makeLinkObj( $nt, $text, "", $trail );
1020 }
1021 wfProfileOut( $fname );
1022 return $s;
1023 }
1024
1025 # Some functions here used by doBlockLevels()
1026 #
1027 /* private */ function closeParagraph()
1028 {
1029 $result = "";
1030 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1031 0 != strcmp( "", $this->mLastSection ) ) {
1032 $result = "</" . $this->mLastSection . ">";
1033 }
1034 $this->mLastSection = "";
1035 return $result;
1036 }
1037 # getCommon() returns the length of the longest common substring
1038 # of both arguments, starting at the beginning of both.
1039 #
1040 /* private */ function getCommon( $st1, $st2 )
1041 {
1042 $fl = strlen( $st1 );
1043 $shorter = strlen( $st2 );
1044 if ( $fl < $shorter ) { $shorter = $fl; }
1045
1046 for ( $i = 0; $i < $shorter; ++$i ) {
1047 if ( $st1{$i} != $st2{$i} ) { break; }
1048 }
1049 return $i;
1050 }
1051 # These next three functions open, continue, and close the list
1052 # element appropriate to the prefix character passed into them.
1053 #
1054 /* private */ function openList( $char )
1055 {
1056 $result = $this->closeParagraph();
1057
1058 if ( "*" == $char ) { $result .= "<ul><li>"; }
1059 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1060 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1061 else if ( ";" == $char ) {
1062 $result .= "<dl><dt>";
1063 $this->mDTopen = true;
1064 }
1065 else { $result = "<!-- ERR 1 -->"; }
1066
1067 return $result;
1068 }
1069
1070 /* private */ function nextItem( $char )
1071 {
1072 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1073 else if ( ":" == $char || ";" == $char ) {
1074 $close = "</dd>";
1075 if ( $this->mDTopen ) { $close = "</dt>"; }
1076 if ( ";" == $char ) {
1077 $this->mDTopen = true;
1078 return $close . "<dt>";
1079 } else {
1080 $this->mDTopen = false;
1081 return $close . "<dd>";
1082 }
1083 }
1084 return "<!-- ERR 2 -->";
1085 }
1086
1087 /* private */function closeList( $char )
1088 {
1089 if ( "*" == $char ) { return "</li></ul>"; }
1090 else if ( "#" == $char ) { return "</li></ol>"; }
1091 else if ( ":" == $char ) {
1092 if ( $this->mDTopen ) {
1093 $this->mDTopen = false;
1094 return "</dt></dl>";
1095 } else {
1096 return "</dd></dl>";
1097 }
1098 }
1099 return "<!-- ERR 3 -->";
1100 }
1101
1102 /* private */ function doBlockLevels( $text, $linestart )
1103 {
1104 $fname = "OutputPage::doBlockLevels";
1105 wfProfileIn( $fname );
1106 # Parsing through the text line by line. The main thing
1107 # happening here is handling of block-level elements p, pre,
1108 # and making lists from lines starting with * # : etc.
1109 #
1110 $a = explode( "\n", $text );
1111 $text = $lastPref = "";
1112 $this->mDTopen = $inBlockElem = false;
1113
1114 if ( ! $linestart ) { $text .= array_shift( $a ); }
1115 foreach ( $a as $t ) {
1116 if ( "" != $text ) { $text .= "\n"; }
1117
1118 $oLine = $t;
1119 $opl = strlen( $lastPref );
1120 $npl = strspn( $t, "*#:;" );
1121 $pref = substr( $t, 0, $npl );
1122 $pref2 = str_replace( ";", ":", $pref );
1123 $t = substr( $t, $npl );
1124
1125 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1126 $text .= $this->nextItem( substr( $pref, -1 ) );
1127
1128 if ( ";" == substr( $pref, -1 ) ) {
1129 $cpos = strpos( $t, ":" );
1130 if ( ! ( false === $cpos ) ) {
1131 $term = substr( $t, 0, $cpos );
1132 $text .= $term . $this->nextItem( ":" );
1133 $t = substr( $t, $cpos + 1 );
1134 }
1135 }
1136 } else if (0 != $npl || 0 != $opl) {
1137 $cpl = $this->getCommon( $pref, $lastPref );
1138
1139 while ( $cpl < $opl ) {
1140 $text .= $this->closeList( $lastPref{$opl-1} );
1141 --$opl;
1142 }
1143 if ( $npl <= $cpl && $cpl > 0 ) {
1144 $text .= $this->nextItem( $pref{$cpl-1} );
1145 }
1146 while ( $npl > $cpl ) {
1147 $char = substr( $pref, $cpl, 1 );
1148 $text .= $this->openList( $char );
1149
1150 if ( ";" == $char ) {
1151 $cpos = strpos( $t, ":" );
1152 if ( ! ( false === $cpos ) ) {
1153 $term = substr( $t, 0, $cpos );
1154 $text .= $term . $this->nextItem( ":" );
1155 $t = substr( $t, $cpos + 1 );
1156 }
1157 }
1158 ++$cpl;
1159 }
1160 $lastPref = $pref2;
1161 }
1162 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1163 if ( preg_match(
1164 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1165 $text .= $this->closeParagraph();
1166 $inBlockElem = true;
1167 }
1168 if ( ! $inBlockElem ) {
1169 if ( " " == $t{0} ) {
1170 $newSection = "pre";
1171 # $t = wfEscapeHTML( $t );
1172 }
1173 else { $newSection = "p"; }
1174
1175 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1176 $text .= $this->closeParagraph();
1177 $text .= "<" . $newSection . ">";
1178 } else if ( 0 != strcmp( $this->mLastSection,
1179 $newSection ) ) {
1180 $text .= $this->closeParagraph();
1181 if ( 0 != strcmp( "p", $newSection ) ) {
1182 $text .= "<" . $newSection . ">";
1183 }
1184 }
1185 $this->mLastSection = $newSection;
1186 }
1187 if ( $inBlockElem &&
1188 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1189 $inBlockElem = false;
1190 }
1191 }
1192 $text .= $t;
1193 }
1194 while ( $npl ) {
1195 $text .= $this->closeList( $pref2{$npl-1} );
1196 --$npl;
1197 }
1198 if ( "" != $this->mLastSection ) {
1199 if ( "p" != $this->mLastSection ) {
1200 $text .= "</" . $this->mLastSection . ">";
1201 }
1202 $this->mLastSection = "";
1203 }
1204 wfProfileOut( $fname );
1205 return $text;
1206 }
1207
1208 /* private */ function replaceVariables( $text )
1209 {
1210 global $wgLang;
1211 $fname = "OutputPage::replaceVariables";
1212 wfProfileIn( $fname );
1213
1214
1215 # Basic variables
1216 # See Language.php for the definition of each magic word
1217
1218 # As with sigs, this uses the server's local time -- ensure
1219 # this is appropriate for your audience!
1220 $v = date( "m" );
1221 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1222 $text = $mw->replace( $v, $text );
1223
1224 $v = $wgLang->getMonthName( date( "n" ) );
1225 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1226 $text = $mw->replace( $v, $text );
1227
1228 $v = $wgLang->getMonthNameGen( date( "n" ) );
1229 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1230 $text = $mw->replace( $v, $text );
1231
1232 $v = date( "j" );
1233 $mw = MagicWord::get( MAG_CURRENTDAY );
1234 $text = $mw->replace( $v, $text );
1235
1236 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1237 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1238 $text = $mw->replace( $v, $text );
1239
1240 $v = date( "Y" );
1241 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1242 $text = $mw->replace( $v, $text );
1243
1244 $v = $wgLang->time( wfTimestampNow(), false );
1245 $mw =& MagicWord::get( MAG_CURRENTTIME );
1246 $text = $mw->replace( $v, $text );
1247
1248 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1249 if ( $mw->match( $text ) ) {
1250 $v = wfNumberOfArticles();
1251 $text = $mw->replace( $v, $text );
1252 }
1253
1254 # "Variables" with an additional parameter e.g. {{MSG:wikipedia}}
1255 # The callbacks are at the bottom of this file
1256 $mw =& MagicWord::get( MAG_MSG );
1257 $text = $mw->substituteCallback( $text, "wfReplaceMsgVar" );
1258
1259 $mw =& MagicWord::get( MAG_MSGNW );
1260 $text = $mw->substituteCallback( $text, "wfReplaceMsgnwVar" );
1261
1262 wfProfileOut( $fname );
1263 return $text;
1264 }
1265
1266 # Cleans up HTML, removes dangerous tags and attributes
1267 /* private */ function removeHTMLtags( $text )
1268 {
1269 $fname = "OutputPage::removeHTMLtags";
1270 wfProfileIn( $fname );
1271 $htmlpairs = array( # Tags that must be closed
1272 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1273 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1274 "strike", "strong", "tt", "var", "div", "center",
1275 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1276 "ruby", "rt" , "rb" , "rp"
1277 );
1278 $htmlsingle = array(
1279 "br", "p", "hr", "li", "dt", "dd"
1280 );
1281 $htmlnest = array( # Tags that can be nested--??
1282 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1283 "dl", "font", "big", "small", "sub", "sup"
1284 );
1285 $tabletags = array( # Can only appear inside table
1286 "td", "th", "tr"
1287 );
1288
1289 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1290 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1291
1292 $htmlattrs = $this->getHTMLattrs () ;
1293
1294 # Remove HTML comments
1295 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1296
1297 $bits = explode( "<", $text );
1298 $text = array_shift( $bits );
1299 $tagstack = array(); $tablestack = array();
1300
1301 foreach ( $bits as $x ) {
1302 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1303 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1304 $x, $regs );
1305 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1306 error_reporting( $prev );
1307
1308 $badtag = 0 ;
1309 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1310 # Check our stack
1311 if ( $slash ) {
1312 # Closing a tag...
1313 if ( ! in_array( $t, $htmlsingle ) &&
1314 ( $ot = array_pop( $tagstack ) ) != $t ) {
1315 array_push( $tagstack, $ot );
1316 $badtag = 1;
1317 } else {
1318 if ( $t == "table" ) {
1319 $tagstack = array_pop( $tablestack );
1320 }
1321 $newparams = "";
1322 }
1323 } else {
1324 # Keep track for later
1325 if ( in_array( $t, $tabletags ) &&
1326 ! in_array( "table", $tagstack ) ) {
1327 $badtag = 1;
1328 } else if ( in_array( $t, $tagstack ) &&
1329 ! in_array ( $t , $htmlnest ) ) {
1330 $badtag = 1 ;
1331 } else if ( ! in_array( $t, $htmlsingle ) ) {
1332 if ( $t == "table" ) {
1333 array_push( $tablestack, $tagstack );
1334 $tagstack = array();
1335 }
1336 array_push( $tagstack, $t );
1337 }
1338 # Strip non-approved attributes from the tag
1339 $newparams = preg_replace(
1340 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1341 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1342 $params);
1343 }
1344 if ( ! $badtag ) {
1345 $rest = str_replace( ">", "&gt;", $rest );
1346 $text .= "<$slash$t$newparams$brace$rest";
1347 continue;
1348 }
1349 }
1350 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1351 }
1352 # Close off any remaining tags
1353 while ( $t = array_pop( $tagstack ) ) {
1354 $text .= "</$t>\n";
1355 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1356 }
1357 wfProfileOut( $fname );
1358 return $text;
1359 }
1360
1361
1362 /*
1363 *
1364 * This function accomplishes several tasks:
1365 * 1) Auto-number headings if that option is enabled
1366 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1367 * 3) Add a Table of contents on the top for users who have enabled the option
1368 * 4) Auto-anchor headings
1369 *
1370 * It loops through all headlines, collects the necessary data, then splits up the
1371 * string and re-inserts the newly formatted headlines.
1372 *
1373 * */
1374 /* private */ function formatHeadings( $text )
1375 {
1376 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1377 $nh=$wgUser->getOption( "numberheadings" );
1378 $st=$wgUser->getOption( "showtoc" );
1379 if(!$wgTitle->userCanEdit()) {
1380 $es=0;
1381 $esr=0;
1382 } else {
1383 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1384 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1385 }
1386
1387 # Inhibit editsection links if requested in the page
1388 if ($es) {
1389 $esw=& MagicWord::get(MAG_NOEDITSECTION);
1390 if ($esw->matchAndRemove( $text )) {
1391 $es=0;
1392 }
1393 }
1394 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1395 # do not add TOC
1396 $mw =& MagicWord::get( MAG_NOTOC );
1397 if ($mw->matchAndRemove( $text ))
1398 {
1399 $st = 0;
1400 }
1401
1402 # never add the TOC to the Main Page. This is an entry page that should not
1403 # be more than 1-2 screens large anyway
1404 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1405
1406 # We need this to perform operations on the HTML
1407 $sk=$wgUser->getSkin();
1408
1409 # Get all headlines for numbering them and adding funky stuff like [edit]
1410 # links
1411 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1412
1413 # headline counter
1414 $c=0;
1415
1416 # Ugh .. the TOC should have neat indentation levels which can be
1417 # passed to the skin functions. These are determined here
1418 foreach($matches[3] as $headline) {
1419 if($level) { $prevlevel=$level;}
1420 $level=$matches[1][$c];
1421 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1422
1423 $h[$level]=0; // reset when we enter a new level
1424 $toc.=$sk->tocIndent($level-$prevlevel);
1425 $toclevel+=$level-$prevlevel;
1426
1427 }
1428 if(($nh||$st) && $level<$prevlevel) {
1429 $h[$level+1]=0; // reset when we step back a level
1430 $toc.=$sk->tocUnindent($prevlevel-$level);
1431 $toclevel-=$prevlevel-$level;
1432
1433 }
1434 $h[$level]++; // count number of headlines for each level
1435
1436 if($nh||$st) {
1437 for($i=1;$i<=$level;$i++) {
1438 if($h[$i]) {
1439 if($dot) {$numbering.=".";}
1440 $numbering.=$h[$i];
1441 $dot=1;
1442 }
1443 }
1444 }
1445
1446 // The canonized header is a version of the header text safe to use for links
1447
1448 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1449 $tocline=$canonized_headline;
1450 $canonized_headline=str_replace('"',"",$canonized_headline);
1451 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1452 $refer[$c]=$canonized_headline;
1453 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1454 $refcount[$c]=$refers[$canonized_headline];
1455
1456 // Prepend the number to the heading text
1457
1458 if($nh||$st) {
1459 $tocline=$numbering ." ". $tocline;
1460
1461 // Don't number the heading if it is the only one (looks silly)
1462 if($nh && count($matches[3]) > 1) {
1463 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1464 }
1465 }
1466
1467 // Create the anchor for linking from the TOC to the section
1468
1469 $anchor=$canonized_headline;
1470 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1471 if($st) {
1472 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1473 }
1474 if($es && !isset($wpPreview)) {
1475 $head[$c].=$sk->editSectionLink($c+1);
1476 }
1477
1478 // Put it all together
1479
1480 $head[$c].="<h".$level.$matches[2][$c]
1481 ."<a name=\"".$anchor."\">"
1482 .$headline
1483 ."</a>"
1484 ."</h".$level.">";
1485
1486 // Add the edit section link
1487
1488 if($esr && !isset($wpPreview)) {
1489 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1490 }
1491
1492 $numbering="";
1493 $c++;
1494 $dot=0;
1495 }
1496
1497 if($st) {
1498 $toclines=$c;
1499 $toc.=$sk->tocUnindent($toclevel);
1500 $toc=$sk->tocTable($toc);
1501 }
1502
1503 // split up and insert constructed headlines
1504
1505 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1506 $i=0;
1507
1508 foreach($blocks as $block) {
1509 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1510 # This is the [edit] link that appears for the top block of text when
1511 # section editing is enabled
1512 $full.=$sk->editSectionLink(0);
1513 }
1514 $full.=$block;
1515 if($st && $toclines>3 && !$i) {
1516 # Let's add a top anchor just in case we want to link to the top of the page
1517 $full="<a name=\"top\"></a>".$full.$toc;
1518 }
1519
1520 $full.=$head[$i];
1521 $i++;
1522 }
1523
1524 return $full;
1525 }
1526
1527 /* private */ function magicISBN( $text )
1528 {
1529 global $wgLang;
1530
1531 $a = split( "ISBN ", " $text" );
1532 if ( count ( $a ) < 2 ) return $text;
1533 $text = substr( array_shift( $a ), 1);
1534 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1535
1536 foreach ( $a as $x ) {
1537 $isbn = $blank = "" ;
1538 while ( " " == $x{0} ) {
1539 $blank .= " ";
1540 $x = substr( $x, 1 );
1541 }
1542 while ( strstr( $valid, $x{0} ) != false ) {
1543 $isbn .= $x{0};
1544 $x = substr( $x, 1 );
1545 }
1546 $num = str_replace( "-", "", $isbn );
1547 $num = str_replace( " ", "", $num );
1548
1549 if ( "" == $num ) {
1550 $text .= "ISBN $blank$x";
1551 } else {
1552 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1553 "Booksources"), "isbn={$num}" ) . "\" class=\"internal\">ISBN $isbn</a>";
1554 $text .= $x;
1555 }
1556 }
1557 return $text;
1558 }
1559
1560 /* private */ function magicRFC( $text )
1561 {
1562 return $text;
1563 }
1564
1565 /* private */ function headElement()
1566 {
1567 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1568
1569 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1570
1571 if ( "" == $this->mHTMLtitle ) {
1572 $this->mHTMLtitle = $this->mPagetitle;
1573 }
1574 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1575 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1576 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1577 foreach ( $this->mMetatags as $tag ) {
1578 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1579 $a = "http-equiv";
1580 $tag[0] = substr( $tag[0], 5 );
1581 } else {
1582 $a = "name";
1583 }
1584 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1585 }
1586 $p = $this->mRobotpolicy;
1587 if ( "" == $p ) { $p = "index,follow"; }
1588 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1589
1590 if ( count( $this->mKeywords ) > 0 ) {
1591 $ret .= "<meta name=\"keywords\" content=\"" .
1592 implode( ",", $this->mKeywords ) . "\">\n";
1593 }
1594 foreach ( $this->mLinktags as $tag ) {
1595 $ret .= "<link ";
1596 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1597 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1598 $ret .= "href=\"{$tag[2]}\">\n";
1599 }
1600 $sk = $wgUser->getSkin();
1601 $ret .= $sk->getHeadScripts();
1602 $ret .= $sk->getUserStyles();
1603
1604 $ret .= "</head>\n";
1605 return $ret;
1606 }
1607 }
1608
1609 # Regex callbacks, used in OutputPage::replaceVariables
1610
1611 # Just get rid of the dangerous stuff
1612 # Necessary because replaceVariables is called after removeHTMLtags,
1613 # and message text can come from any user
1614 function wfReplaceMsgVar( $matches ) {
1615 global $wgOut;
1616 $text = $wgOut->removeHTMLtags( wfMsg( $matches[1] ) );
1617 return $text;
1618 }
1619
1620 # Effective <nowiki></nowiki>
1621 # Not real <nowiki> because this is called after nowiki sections are processed
1622 function wfReplaceMsgnwVar( $matches ) {
1623 $text = wfEscapeWikiText( wfMsg( $matches[1] ) );
1624 return $text;
1625 }
1626
1627 ?>